(function(KDApi){
    function MyComponent(model){
        this._setModel(model);
    }
    
	var stamp = 0;// 记录是否是第一次加载的记录戳
	var startLngLat=[];// 初始化出发地坐标
	var endLngLat=[];// 初始化目的地坐标
    MyComponent.prototype = {
        _setModel: function(model) {
            this.model = model;
        },
        init:function(props){
		  setHtml(this.model,props);
          console.log('-----initclz',this.model,props);
          debugger;
		  stamp = 1;
        },
        update:function(props){
			console.log('-----update',this.model,props);
			// 判断是否是向列表页面跳转(true:清空地图的dom，防止页面缓存不清除跳转回来时不重新加载)
			if(null!=props.data&&props.data.listReturn!="undefined"&&props.data.listReturn==1){
				var box=document.getElementById("mapContainer");
				box.remove();// 清除map的dom
				stamp = 0;// 重置记录戳
				startLngLat=[];// 重置坐标防止页面缓存记录
				endLngLat=[];
				return;// 重置dom后不向下执行
			}	
			if(stamp>1){// 如果记录戳大于1表示非初始化进入即执行更新
				setHtml(this.model,props);  
			}
			stamp = 2;// 初始化进入时改记录戳为2
        },
        destoryed:function(){// 暂未使用
            console.log('-----destoryed',this.model);
        }
    }

    var setHtml = function(model,props){
		KDApi.loadFile('./css/avatar.css',model,() => {
            KDApi.templateFilePath('./html/avatar.html',model,null).then(result => {				
                model.dom.innerHTML = result			   
                console.log(result);
                initEvent(model,props);
            })
        })		
    };
	/*
	 * 动态加载js脚本 调用callback时，js文件已经加载完成
	 */
	var loadScript = function(url, callback) {
		let target = document.getElementById('mapbase');
		if(target){
			callback();
			return;
		}

		let script = document.createElement('script');
		script.id = 'mapbase'; // 唯一标示，防止html文件中重复添加.
		script.type = 'text/javascript';
		if(typeof(callback) != undefined){
			if (script.readyState) {
				script.onreadystatechange = function () {
			    if (script.readyState == 'loaded' || script.readyState == 'complete') {
			      script.onreadystatechange = null;
			      callback();
			    }
			  };
			}else{
				script.onload = function () {
					callback();
				};
			}
		}
		script.src = url;
		document.body.appendChild(script);
	}
	var redata;
	var marker;
   var placeResult = {};
    var initEvent = function(model,props){
		loadScript("https://api.map.baidu.com/getscript?v=3.0&ak=1bj2lIGR29WjoYG18dh7tGRW6eODdWDt",function(){
	
        // loadScript("https://api.map.baidu.com/getscript?type=webgl&v=1.4&ak=1bj2lIGR29WjoYG18dh7tGRW6eODdWDt",function(){
		// 百度地图API功能
	function G(id) {
		return document.getElementById(id);
	}

	var map = new BMap.Map("l-map");
	map.centerAndZoom("深圳",12);                   // 初始化地图,设置城市和地图级别。

	var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
		{"input" : "suggestId"
		,"location" : map
	});

	ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
	var str = "";
		var _value = e.fromitem.value;
		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
		G("searchResultPanel").innerHTML = str;
	});

	var myValue;
	ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
	var _value = e.item.value;
		myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
        placeResult.value=myValue;
		setPlace();
	});
//延迟加载
    var timeoutTmp = setTimeout(() => {
        var tangramSuggestionMainDocuments = document.getElementsByClassName('tangram-suggestion-main');
        for(var i = 0; i < tangramSuggestionMainDocuments.length; i++) {
            var angramSuggestionMain = tangramSuggestionMainDocuments[i];
            angramSuggestionMain.style.zIndex = 1999;
        }
        clearTimeout(timeoutTmp);
    }, 2000);

	function setPlace(){
		map.clearOverlays();    //清除地图上所有覆盖物
		function myFun(){
			var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            placeResult.point=pp;
            placeResult.result=local.getResults();
			map.centerAndZoom(pp, 18);
			map.addOverlay(new BMap.Marker(pp));    //添加标注
              model.invoke('updateData',placeResult);
		}
		var local = new BMap.LocalSearch(map, { //智能搜索
		  onSearchComplete: myFun
		});
		local.search(myValue);
	}
	});	

    }
    KDApi.register('ivatar_search', MyComponent)
})(window.KDApi);